import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.postgresql.jdbc.PgConnection;

/**
 * @作者 ： pwx5328113 @时间： 2023/3/7
 * @测试点: 打开快速负载均衡，3个节点，初始2个节点正常，1个节点恢复时，1个节点有50%活跃连接，1个节点有30%活跃连接,且其他连接空闲IDLE超过30s
 **/
public class JDBC_QuikAutoBalance_Case0019 {
	public static void main(String[] args) throws Exception {
		System.out.println("----------start----------");
		// start前，args[0] 包含3个节点，其中一个节点异常
		System.out.println("----------进行30个建连----------");
		Map<String, List<PgConnection>> connectionMap = new HashMap<>();
		// 创建30条连接，根据目的端ip分别保存到connectionMap
		int num = 30;
		for (int i = 0; i < num; i++) {
			String url = "jdbc:postgresql://" + args[0] + "/" + args[1] + "?" + args[4];
			PgConnection connection1 = DriverManager.getConnection(url, args[2], args[3]).unwrap(PgConnection.class);
			String socketAddress = connection1.getSocketAddress();
			String[] split = socketAddress.split("/");
			System.out.println(split[1]);
			String address = split[1];
			if (!connectionMap.containsKey(address)) {
				connectionMap.put(address, new ArrayList<>());
			}
			List<PgConnection> list = connectionMap.get(address);
			list.add(connection1);
		}
		// 遍历所有的节点，每个节点上一部分连接繁忙，一部分连接空闲
		TimeUnit.SECONDS.sleep(30);
		int index = 0;
		for (Map.Entry<String, List<PgConnection>> entry : connectionMap.entrySet()) {
			if (index == 0) {
				String str = entry.getKey();
				System.out.println("ip: " + str);
				List<PgConnection> pgConnections = entry.getValue();
				System.out.println("connection count: " + pgConnections.size());
				for (int i = 0; i < pgConnections.size() * 0.5; i++) {
					pgConnections.get(i).isValid(3);
					System.out.println("ip1 " + pgConnections.get(i));
				}
			} else {
				String str = entry.getKey();
				System.out.println("ip: " + str);
				List<PgConnection> pgConnections = entry.getValue();
				System.out.println("connection count: " + pgConnections.size());
				for (int i = 0; i < pgConnections.size() * 0.3; i++) {
					pgConnections.get(i).isValid(3);
					System.out.println("ip2 " + pgConnections.get(i));
				}
			}
			index++;
		}
		System.out.println("----------sleep 45s----------");
		// 查询剩余连接
		TimeUnit.SECONDS.sleep(45);
		System.out.println("----------close connection----------");
		for (Map.Entry<String, List<PgConnection>> entry : connectionMap.entrySet()) {
			String str = entry.getKey();
			System.out.println("ip: " + str);
			List<PgConnection> pgConnections = entry.getValue();
			System.out.println("connection count: " + pgConnections.size());
			for (Connection connection : pgConnections) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
